package com.bsit.obu.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;

import com.bsit.obu.base.BaseApplication;
import com.bsit.obu.constant.CommonConstant;
import com.bsit.obu.constant.Constants;
import com.bsit.obu.dialog.LoadingDialog;
import com.bsit.obu.model.CarSecondPublicInfo;
import com.bsit.obu.model.CardInfo;
import com.bsit.obu.model.ObuInfo;
import com.bsit.obu.model.ObuStatus;



import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by DELL on 2016/5/17.
 */
public class CommonUtil {

    private static String TAG = "TAG";

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }





    /**
     * 跳转至设置vpn
     * @param context
     */
    public static void toVpnSetting(Context context){
        Intent intent = new Intent("android.net.vpn.SETTINGS");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        if(intent.resolveActivity(context.getPackageManager())==null){
        }else {
            context.startActivity(intent);
        }
    }


    /**
     * 检查网络连接状态(也可以拓展为判断是wifi还是移动流量)
     */
    public static boolean isNetConnected(final Context context) {
        boolean hasWifoCon = false;
        boolean hasMobileCon = false;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfos = cm.getAllNetworkInfo();
        for (NetworkInfo net : netInfos) {

            String type = net.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                Log.e(TAG, "get Wifi connection");
                if (net.isConnected()) {
                    hasWifoCon = true;
                }
            }

            if (type.equalsIgnoreCase("MOBILE")) {
                Log.e(TAG, "get Mobile connection");
                if (net.isConnected()) {
                    hasMobileCon = true;
                }
            }
        }
        return hasWifoCon || hasMobileCon;

    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 解析板子返回信息(不含个性化数据)
     * @param buffer
     */
    public static ObuInfo parseBoardInfo(byte[] buffer) {
        if(buffer.length!=31){
            return null;
        }

        String obuData = ByteUtil.byte2HexStr(buffer);
        ObuInfo obuInfo = new ObuInfo();
        //C9BDB6ABC9BDB6AB
        // 00
        // 11
        // 3702491600000087
        // 20110101
        // 20201231
        // 0000000000CEFF000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

        /**发行方标识*/
        try {
            String  infoCode =new String(buffer,0,4,"GB2312");
            obuInfo.setInfoCode(infoCode + ByteUtil.byte2HexStr(new byte[]{buffer[4],buffer[5],buffer[6],buffer[7]}));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        /**协约类型*/
        obuInfo.setProtelType(String.valueOf(buffer[8]));
        /**合同版本*/
        obuInfo.setContractVersion(Integer.toHexString(buffer[9] & 0XFF));
        /**合同序列号*/
        obuInfo.setSerlNo(obuData.substring(20, 36));
        /**合同签署日期，格式:CCYYMMDD*/
        obuInfo.setContractMarkdate(String.format("%02X%02X.%02X.%02X", buffer[18], buffer[19],buffer[20], buffer[21]));
        /**合同过期日期，格式:CCYYMMDD*/
        obuInfo.setContractOverdueDate(String.format("%02X%02X.%02X.%02X",  buffer[22], buffer[23], buffer[24], buffer[25]));
        /**拆卸状态*/
        obuInfo.setDisassemblyState(ObuStatus.getContent(buffer[26]));
        /**Mac*/
       // obuInfo.setMAC(ByteUtil.byte2HexStr(new byte[]{buffer[27],buffer[28],buffer[29],buffer[30]}));
        MyLog.d(MyLog.TAG,"obuInfo=="+obuInfo.toString());
        return obuInfo;
    }

    /**
     * 解析车牌号信息
     * @param carPlateNoArray 12个字节的车牌号信息
     * @return
     */
    public static String parseCarPlateInfo(byte[] carPlateNoArray) {
        String carNum = "";
        try {
            carNum = new String(carPlateNoArray,0,carPlateNoArray.length,"GB2312");
            carNum = carNum.replaceAll("[\u0000]", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "解析车牌号出错";
        }
        return carNum;
    }


    /**
     * 解析车牌颜色
     * @param b 高八位
     * @param b1 第八位
     *                *     *  BLUE(0, " 蓝色 "),
     *      *      *     YELLOW(1, "黄色"),
     *      *      *     BLACK(2, "黑色"),
     *      *      *     WHITE(3, "白色"),
     *      *      *     JIANBIAN_LVSE(4, "渐变绿色"),
     *      *      *     HUANGLV(5, "黄绿双拼色"),
     *      *      *     LANBAI(6, "蓝白渐变色"),
     *      *      *     GREEN(11, "绿色"),
     *      *      *     RED(12, "红色");
     * @return
     */

    public static String parsePlateColor(byte b, byte b1) {
        int result = byte2ToInt(new byte[]{b,b1});
        MyLog.e(TAG,"result=="+result);
        if (result == (byte)0x00){
            return "蓝色";
        } else if (result == (byte)0x01){
            return "黄色";
        } else if (result == (byte)0x02){
            return "黑色";
        } else if (result == (byte)0x03){
            return "白色";
        }else if (result == (byte)0x04){
            return "渐变绿色";
        }else if (result == (byte)0x05){
            return "黄绿双拼色";
        }else if (result == (byte)0x06){
            return "蓝白渐变色";
        }else if (result == (byte)0x0B){
            return "绿色";
        }else if (result == (byte)0x0C){
            return "红色";
        }

        return "蓝色";
    }
    /**
     * 解析车的长宽高
     * @param b 长的高八位
     * @param b1 长的低八位
     * @param b2 宽的二进制数
     * @param b3 高的二进制
     * @param b4
     * @param b5
     * @return 返回长宽高数据（如：8000 * 1700 * 4000）；
     */
    public static String parseCarSize(byte b, byte b1, byte b2, byte b3, byte b4, byte b5) {
//        int lenth = ((int)b * 0xFF + b1) * 100;
//        int width = b2 * 100;
//        int height = b3 * 100;
        //012C 9696 3264
        int lenth = byte2ToInt(new byte[]{b,b1});
        int width = byte2ToInt(new byte[]{b2,b3});
        int height = byte2ToInt(new byte[]{b4,b5});
       /*
        int lenth = ((int)b * 0xFF + b1) ;
        int width = ((int)b2 * 0xFF + b3) ;
        int height = ((int)b4 * 0xFF + b5) ;*/
        return lenth + "*" + width + "*" + height;
    }
//    0 – 普通用户
//    6 – 公务车用户
//    8 – 军警车用户
//    10 – 紧急车用户
//    12 – 免费用户
//    14 – 车队用户
//    15 – 内部优惠（车卡绑定）
//    16 – 社会优惠（车卡绑定）
//    21  - 客车无OBU用户
//    22  - 货车用户


    /**
     * @param userType
     * @return
     */
    public static String parseUsertype(byte userType) {
        byte[] tmp = new byte[1];
        tmp[0] = userType;
        MyLog.e(MyLog.TAG, "parseUsertype userType----" + ByteUtil.byte2HexStr(tmp));
        switch (userType){
            case 0x01:
                return "个人用户";
            case 0x02:
                return "单位用户";

        }
        return "普通用户";
    }



    /**
     *解析车辆信息
     * @param byteInfo 车辆信息
     * @return
     */
    public static CarSecondPublicInfo parseCarPalteInfo(byte[] byteInfo) {
        CarSecondPublicInfo carInfo = new CarSecondPublicInfo();
        byte[] carPlateNo = new byte[12];
        int index = 0;
        System.arraycopy(byteInfo,index,carPlateNo,0, carPlateNo.length);
        carInfo.setPalteNo(CommonUtil.parseCarPlateInfo(carPlateNo));
        index+=carPlateNo.length;
        carInfo.setPlateColor(CommonUtil.parsePlateColor(byteInfo[index],byteInfo[index+1]));
        index +=2;
        carInfo.setCarType(byteInfo[index++]);//车型
        carInfo.setUserType(CommonUtil.parseUsertype(byteInfo[index++]));
        carInfo.setPlataSize(CommonUtil.parseCarSize(byteInfo[index++],byteInfo[index++],byteInfo[index++],byteInfo[index++],byteInfo[index++],byteInfo[index++]));

        int tractionMass = CommonUtil.byte3ToInt(new byte[]{byteInfo[index++],byteInfo[index++],byteInfo[index++]});//核定载质量/准牵引总质量(kg)
        carInfo.setTractionMass(tractionMass);
        int curbWeight = CommonUtil.byte3ToInt(new byte[]{byteInfo[index++],byteInfo[index++],byteInfo[index++]});//整备质量(kg)
        carInfo.setCurbWeight(curbWeight);

        int totalMass = CommonUtil.byte3ToInt(new byte[]{byteInfo[index++],byteInfo[index++],byteInfo[index++]});//车辆总质量(kg)
        carInfo.setTotalMass(totalMass);
        carInfo.setPassagerCapacity(byteInfo[index++]);
        //车辆识别代码
        try {
            carInfo.setEngineNo(new  String(byteInfo,index,17,"GB2312"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        index+=17;

        //车辆特征描述
        try {
            carInfo.setMessageCode(new  String(byteInfo,index++,16,"GB2312"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        MyLog.d(MyLog.TAG, index + "    carInfo is : " + carInfo.toString());
        return carInfo;
    }

    /**
     * 根据卡类型代码，返回相应字符串
     * @param b 1：储蓄卡 2，记账卡 3，公务卡， 其他
     * @return
     */
    private static String getCardType(byte b) {
        switch (b){
            case 22:
                return "储蓄卡";
            case 23:
                return "记账卡";
            default:
                return "储蓄卡";
        }
    }

    /**
     * 解析余额
     * @param amountArray
     * @return
     */
    public static String getBalance(byte[] amountArray) {
        long amount = getLong(amountArray,true);
        float result = amount/100.0f;
        DecimalFormat df   = new DecimalFormat("######0.00");
        return df.format(result);
    }

    /**
     * byte数组转换为int整数
     *
     * @param bytes
     *            byte数组
     * @return int整数
     */
    public static int byte3ToInt(byte[] bytes) {
        int b0 = bytes[0] & 0xFF;
        int b1 = bytes[1] & 0xFF;
        int b2 = bytes[2] & 0xFF;
        return (b0 << 16) | (b1 << 8) | b2;
    }
    /**
     * byte数组转换为int整数
     *
     * @param bytes
     *            byte数组
     * @return int整数
     */
    public static int byte2ToInt(byte[] bytes) {
        int b0 = bytes[0] & 0xFF;
        int b1 = bytes[1] & 0xFF;
        return (b0 << 8) | b1;
    }

    /**
     * byte数组转换为int整数
     *
     * @param bytes
     *            byte数组
     * @param off
     *            开始位置
     * @return int整数
     */
    private static long byte4ToInt(byte[] bytes, int off) {
        int b0 = bytes[off] & 0xFF;
        int b1 = bytes[off + 1] & 0xFF;
        int b2 = bytes[off + 2] & 0xFF;
        int b3 = bytes[off + 3] & 0xFF;
        return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
    }
    public static int getInt(byte[] buf, boolean bBigEnding) {
        if (buf == null) {
            throw new IllegalArgumentException("byte array is null!");
        }

        if (buf.length > 4) {
            throw new IllegalArgumentException("byte array size > 4 !");
        }

        int r = 0;
        if (bBigEnding) {
            for (int i = 0; i < buf.length; i++) {
                r <<= 8;
                r |= (buf[i] & 0x000000ff);
            }
        } else {
            for (int i = buf.length - 1; i >= 0; i--) {
                r <<= 8;
                r |= (buf[i] & 0x000000ff);
            }
        }

        return r;
    }

    public static long getLong(byte[] buf, boolean bBigEnding) {
        if (buf == null) {
            throw new IllegalArgumentException("byte array is null!");
        }

        if (buf.length > 8) {
            throw new IllegalArgumentException("byte array size > 8 !");
        }

        long r = 0;
        if (bBigEnding) {
            for (int i = 0; i < buf.length; i++) {
                r <<= 8;
                r |= (buf[i] & 0x00000000000000ff);
            }
        } else {
            for (int i = buf.length - 1; i >= 0; i--) {
                r <<= 8;
                r |= (buf[i] & 0x00000000000000ff);
            }
        }

        return r;
    }

    /**
     * 去除buffer中的敏感字符，FE01 == FF, FE00 = FE;
     * @param buffer
     * @return
     */
    public static byte[] preTreatData( byte[] buffer) {
        String dataStr = ByteUtil.byte2HexStr(buffer);
        if (dataStr.contains("FE00") || dataStr.contains("FE01")){
            if(dataStr.contains("FE00") && dataStr.indexOf("FE00") % 2 == 0){
                dataStr = dataStr.replaceAll("FE00","FE");
            }
            if(dataStr.contains("FE01") && dataStr.indexOf("FE01") % 2 == 0){
                dataStr = dataStr.replaceAll("FE01","FF");
            }
            return ByteUtil.hexStr(dataStr);
        }
        return buffer;
    }

    /**
     * 去除buffer中的敏感字符，FE01 == FF, FE00 = FE;
     * @param buffer
     * @return String 类型
     */
    public static String preTreatDataStr( byte[] buffer) {
        String dataStr = ByteUtil.byte2HexStr(buffer);
        if (dataStr.contains("FE00") || dataStr.contains("FE01")){
            if(dataStr.contains("FE00") && dataStr.indexOf("FE00") % 2 == 0){
                dataStr = dataStr.replaceAll("FE00","FE");
            }
            if(dataStr.contains("FE01") && dataStr.indexOf("FE01") % 2 == 0){
                dataStr = dataStr.replaceAll("FE01","FF");
            }
            return dataStr;
        }
        return "";
    }

    public static String preTreatData( String dataStr) {
        if (dataStr.contains("FE00") || dataStr.contains("FE01")){
            if(dataStr.contains("FE00") && dataStr.indexOf("FE00") % 2 == 0){
                dataStr = dataStr.replaceAll("FE00","FE");
            }
            if(dataStr.contains("FE01") && dataStr.indexOf("FE01") % 2 == 0){
                dataStr = dataStr.replaceAll("FE01","FF");
            }
        }
        return dataStr;
    }

    /**
     * 解析车型
     * 01：客一；02：客二；03：客三；04：客四；11：货一；12：货二；13：货三；14：货四；15：货五；16：货六；21：集一
     * @param colorStr
     * @return
     */
    public static byte parseCarType(String colorStr){
        switch (colorStr){
            case "客一":
                return(byte)0x01;
            case "客二":
                return(byte)0x02;
            case "客三":
                return(byte)0x03;
            case "客四":
                return(byte)0x04;
            case "货一":
                return(byte)0x11;
            case "货二":
                return(byte)0x12;
            case "货三":
                return(byte)0x13;
            case "货四":
                return(byte)0x14;
            case "货五":
                return(byte)0x15;
            case "货六":
                return(byte)0x16;
            case "集一":
                return(byte)0x21;
        }
        return(byte)0xFF;
    }

    public static String parseStringCarType(byte colorByte){
        byte[] tmp = new byte[1];
        tmp[0] = colorByte;
        MyLog.e(MyLog.TAG, "parseStringCarType colorByte---" + ByteUtil.byte2HexStr(tmp));
        switch (colorByte){
            case 0x01:
                return "客一";
            case 0x02:
                return "客二";
            case 0x03:
                return "客三";
            case 0x04:
                return "客四";
            case 0x11:
                return "货一";
            case 0x12:
                return "货二" ;
            case 0x13:
                return"货三" ;
            case 0x14:
                return "货四";
            case 0x15:
                return"货五" ;
            case 0x16:
                return "货六";
            case 0x21:
                return "集一";
        }
        return "未知";
    }


    public static String getRandom() {
        String random = String.valueOf(System.currentTimeMillis());
        return random.substring(random.length() - 8);
    }
    public static String getTime(){
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dtStr = sdf.format(now);
        Log.e(TAG,dtStr);
        return dtStr;
    }

    /**
     * 获取指纹码，对value 进行3des加密 和对initData进行3Mac加密
     * @param values
     * @return
     */
    public static String getFingerCode(String values) {
        try{
            String value1 = DES.encryptDES(values, CommonConstant.KEY1.substring(0,CommonConstant.KEY1.length()/2));
            String value2 = DES.decryptDES(value1, CommonConstant.KEY1.substring(CommonConstant.KEY1.length()/2));
            String value3 = DES.encryptDES(value2, CommonConstant.KEY1.substring(0,CommonConstant.KEY1.length()/2));
            String result = MAC(value3, CommonConstant.KEY2,CommonConstant.INIT_DATA);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private static String MAC(String plaintext,String keyString,String InitString)
    {
        String temp;
        int i,length,keyLen,numBlock;

        length=plaintext.length();
        keyLen=keyString.length();

        //最后一块补齐。
        if (length%16==0)
            plaintext+="8000000000000000";
        else
        {
            i=0;
            while(i<(16-length%16))
            {
                if (i==0)
                {
                    plaintext+="80";
                    i+=2;
                }
                else
                {
                    plaintext+="0";
                    i++;
                }
            }
        }

        length=plaintext.length();
        numBlock=length/16;
        try{


            for (i=0;i<numBlock;i++)
            {
                temp=plaintext.substring(i*16,i*16+16);
                InitString=HexXor(InitString,temp);
                if (keyLen==16)
                    InitString=DES.encryptDES(InitString,keyString);
                else
                    InitString=DES.encryptDES(InitString,keyString.substring(0,16));
            }

            if (keyLen==32)
            {
                InitString=DES.decryptDES(InitString,keyString.substring(16,32));
                InitString=DES.encryptDES(InitString,keyString.substring(0,16));
            }

        }catch (Exception e){

        }
        return InitString.substring(0,8);
    }

    /**
     * 3des运算用
     * @param s1
     * @param s2
     * @return
     */
    public static String HexXor(String s1,String s2)
    {
        byte[] s1Byte = ByteUtil.hexStr(s1);
        byte[] s2Byte = ByteUtil.hexStr(s2);
        int shortInt,longInt;
        if(s1Byte.length<s2Byte.length){
            shortInt = s1Byte.length;
            longInt = s2Byte.length;
        } else {
            shortInt = s2Byte.length;
            longInt = s1Byte.length;
        }
        byte[] resultByte = new byte[longInt];
        for (int i = 0; i< shortInt; i++){
            resultByte[i] = (byte) (s1Byte[i]^s2Byte[i]);
        }
        for (int i = shortInt; i< longInt ; i++){
            resultByte[i] = 1;
        }

        return ByteUtil.byte2HexStr(resultByte);
    }

    public static String getValus(String random) {
        return CommonConstant.TERMINAL_ID + CommonConstant.FACTORY_ID + CommonConstant.CARD_ID + CommonConstant.AUTHCODE + random;
    }

    public static String getFlage(String state) {
        switch (state){
            case Constants.OUB_RUN_SUCEESS :
                return "1";
            case Constants.OUB_RUN_FAIL :
                return "";
        }
        return null;
    }



    /**
     * 显示对话框
     * @param message
     */
    public static void showDialog(LoadingDialog dialog,Context context,String message){
        if (dialog == null){
            dialog = new LoadingDialog(context,message) ;
        }
        dialog.show();
    }


    public static String getMesLen(String content){
        String a = "00000000";
        int length =content.length();//100
        String varLength = length+"";//"100"
        return  a.substring(0,8 - varLength.length())+length;
    }

    public static String generateBill(String data) {
        String result = "";
      if(data.length()<=1){
          result = "0"+data;
      }else if(data.length()>1&&data.length()<=2){
          result = data;
      }
      return result;
    }

    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phone);
        return  m.matches();
    }
    public static boolean isCarNum(String carPlateNum){
        String regex = "^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z0-9]{1}[A-Z0-9]{1}([京津沪渝桂蒙宁新藏冀晋辽吉黑苏浙皖赣闽鲁粤鄂湘豫川云贵陕甘青琼])?[A-NP-Z0-9]{1}[A-NP-Z0-9]{3}([A-NP-Z0-9挂学警港澳领试超外]{1}|应急)([A-NP-Z0-9外])?)$|^([A-Z0-9]{7})$|^默A00000$|^(应急[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z0-9]{1}[A-NP-Z0-9]{4})$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(carPlateNum);
        return  m.matches();
    }

    /**
     * 得到当前应用版本名称的方法
     *
     * @param context
     *            :上下文
     * @throws Exception
     */
    public static int getVersionName(Context context) throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        int version = packInfo.versionCode;

        return version;
    }

    public static String removeRemainCharFromString(String content,char romeveChar){
        String result = "";
        for(int i = 0;i<content.length();i++){
            if(content.charAt(i) != romeveChar){
                result += content.charAt(i);
            }
        }
        return result;

    }

    public static void openInit(){
        String[] files = new String[]{"/sys/devices/soc.0/xt_dev.68/xt_dc_in_en", "/sys/devices/soc.0/xt_dev.68/xt_vbat_out_en",
                "/sys/devices/soc.0/xt_dev.68/xt_gpio_112", "/sys/devices/soc.0/xt_dev.68/xt_uart_a", "/sys/devices/soc.0/xt_dev.68/xt_uart_b"};
        byte[] data = new byte[]{0x31, 0x31, 0x30, 0x30, 0x31};
        for (int i = 0; i < files.length; i++) {
            writeMediaState(files[i], data[i]);
        }
    }

    public static void closeInit(){
        String[] files = new String[]{"/sys/devices/soc.0/xt_dev.68/xt_dc_in_en", "/sys/devices/soc.0/xt_dev.68/xt_vbat_out_en",
                "/sys/devices/soc.0/xt_dev.68/xt_uart_a", "/sys/devices/soc.0/xt_dev.68/xt_uart_b"};
        byte[] data = new byte[]{0x30, 0x30, 0x30, 0x30};
        for (int i = 0; i < files.length; i++) {
            writeMediaState(files[i], data[i]);
        }
    }

    private static void writeMediaState(String path, int state) {
        try {
            File file = new File(path);
            FileOutputStream out = new FileOutputStream(file);
            out.write(state);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String getDataLen(String data){
        String result = "";
        int length = data.length()/2;
        String var = Integer.toHexString(length);
        if(var.length()==1){
            result = "000" +var;
        }else if(var.length()==2){
            result = "00" + var;
        }else if(var.length()==3){
            result = "0" + var;
        }
        return result;
    }
    public static void main(String[] args){
        // //012C 9696 3264
        //        int lenth = ((int)b * 0xFF + b1) ;
        System.out.println(getDataLen("2344444444444"));
    }

}
